package com.yunxiangyue

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.yunxiangyue.app.R
import com.yunxiangyue.room_login_info.LogDao
import com.yunxiangyue.room_login_info.LogDataBase
import com.yunxiangyue.room_login_info.LogInfo
import com.yunxiangyue.server.ConnectExample

class Register_page : AppCompatActivity(), View.OnClickListener, View.OnFocusChangeListener {


    private lateinit var infoList: MutableList<LogInfo>
    private lateinit var InfoDao: LogDao
    private lateinit var phone: EditText
    private lateinit var pwd: EditText
    private lateinit var notarizePwd: EditText
    private var test = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        val actionBar = supportActionBar
        actionBar?.setHomeButtonEnabled(true)
        actionBar?.setDisplayHomeAsUpEnabled(true)
        phone = findViewById(R.id.phone)
        pwd = findViewById(R.id.pwd)
        notarizePwd = findViewById(R.id.notarize_pwd)
        InfoDao = LogDataBase.getLogDatabase(this).logDao()
        val notarize_btn = findViewById<Button>(R.id.nota_btn)
        notarize_btn.setOnClickListener(this)
        pwd.setOnFocusChangeListener(this)
        notarizePwd.setOnFocusChangeListener(this)

        //删除表中数据
//        InfoDao.deleteAll()
//        InfoDao.alterID()

    }

    private fun logInfo(): Boolean {
        var flag:Boolean= true
        if (TextUtils.isEmpty(phone.text.toString())||phone.text.toString().length != 11) {
            Toast.makeText(this, "手机号码不能为空且只能为11位", Toast.LENGTH_LONG).show()
            phone.setText("")
            flag = false
        }
//        if (phone.text.toString().length != 11) {
//            Toast.makeText(this, "手机号码只能是11位", Toast.LENGTH_SHORT).show()
//            phone.setText("")
//            flag= false
//        }
        if (TextUtils.isEmpty(pwd.text.toString())) {
            Toast.makeText(this, "登录密码不能为空", Toast.LENGTH_LONG).show()
            pwd.setText("")
            flag= false
        }
            if (pwd.text.toString().length < 6 || pwd.text.toString().length > 18||notarizePwd.text.toString().length < 6||notarizePwd.text.toString().length > 18) {
            Toast.makeText(this, "密码只能在6—18位", Toast.LENGTH_LONG).show()
            pwd.setText("")
            flag= false
        }

        if (judegePhoneFormat(phone.text.toString())) {
            Toast.makeText(this, "手机号码格式错误", Toast.LENGTH_LONG).show()
            phone.setText("")
            flag= false
        }
        return flag
    }

    private fun judegePhoneFormat(phone: String): Boolean {
        val phoneFormat = "^1[3-9]\\d{9}\$".toRegex()
        if (TextUtils.isEmpty(phone)) {
            return false
        } else {
            return phone.matches(phoneFormat)
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish()
                return true
            }
        }
        return super.onOptionsItemSelected(item);
    }

    val userInfoCallback: (Boolean) -> Unit = { result:Boolean ->
        if (result) {
            Log.d(TAG, "result is success")
        } else {
            Log.e(TAG, "result is failed")
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){

            R.id.nota_btn -> {
                if(phoneJudge()==true&&phonePwdJudge()==true){
                    if(pwdJudge()){
                        if(!test){
                            //查看该用户数据是否在远程数据库存在  不存在则可以注册
                            //调用方法判断是否存在远程中
                            val connectExampleobject = ConnectExample()
                                //如果本地和远程数据库都不存在则建立
                            if(InfoDao.queryByPhone(phone.text.toString())==0){
                                //将用户信息添加至本地数据库和远程数据库  需要同步进行
                                InfoDao.inserInfo(LogInfo(phone.text.toString(),pwd.text.toString()))
                                //添加用户信息至远程的数据库mongodb
                                //调用对象的添加用户的方法
                                Log.d("user","密码是："+pwd.text.toString())
                                connectExampleobject.insertUser(phone.text.toString(),pwd.text.toString(),"", "false","","","","","",userInfoCallback)
                                Toast.makeText(this,"注册成功，该用户已添加至本地和远程数据库",Toast.LENGTH_SHORT).show()
                                //如果本地不存在远程存在则只需要在本地添加

                            }else if(InfoDao.queryByPhone(phone.text.toString())==1){
                                Toast.makeText(this,"注册失败,本地和远程都存在",Toast.LENGTH_SHORT).show()
                                Log.d("user","注册失败,本地和远程都存在")
                                //本地存在但是远程数据库不存在
                            }else if(InfoDao.queryByPhone(phone.text.toString())==1){
                                connectExampleobject.insertUser(phone.text.toString(),pwd.text.toString(), "","false","","","","","", userInfoCallback)
                                Toast.makeText(this,"该账号本地存在，该用户已添加至远程数据库",Toast.LENGTH_SHORT).show()
                            }else if(InfoDao.queryByPhone(phone.text.toString())==0){
                                InfoDao.inserInfo(LogInfo(phone.text.toString(),pwd.text.toString()))
                                Toast.makeText(this,"本地注册成功，该用户已添加至本地数据库",Toast.LENGTH_SHORT).show()
                            }
                        }else{
                            //处于测试阶段，不存入本地数据库
                            //添加用户信息至远程的数据库mongodb
                            val connectExampleobject = ConnectExample()
                            //调用对象的添加用户的方法
                            connectExampleobject.insertUser(phone.text.toString(),pwd.text.toString(), "", "false","","","","","", userInfoCallback)
                            Toast.makeText(this,"注册成功，该用户已添加至mongodb",Toast.LENGTH_SHORT).show()
                        }

                    }
                    if(!pwdJudge()){
                        Toast.makeText(this,"密码前后输入不一致，请重新输入",Toast.LENGTH_SHORT).show()
                        pwd.requestFocus()
                        pwd.setText("")
                        notarizePwd.setText("")
                    }
                }

            }
        }
    }

    private fun pwdJudge():Boolean{
        if(pwd.text.toString()==notarizePwd.text.toString()){
            return true
        }
        return false
    }

    private fun phoneJudge():Boolean{
        var flag = true
        if (TextUtils.isEmpty(phone.text.toString())||phone.text.toString().length != 11) {
            Toast.makeText(this, "手机号码不能为空且只能为11位", Toast.LENGTH_LONG).show()
            phone.requestFocus()
            phone.setText("")
            pwd.setText("")
            notarizePwd.setText("")
            flag = false
        }else if(!judegePhoneFormat(phone.text.toString())){
            Toast.makeText(this, "手机号码格式错误", Toast.LENGTH_LONG).show()
            phone.requestFocus()
            phone.setText("")
            pwd.setText("")
            notarizePwd.setText("")
            flag = false
        }
        return flag
    }

    private fun phonePwdJudge():Boolean{
        var flag = true
        phoneJudge()
        if (TextUtils.isEmpty(pwd.text.toString())) {
            Toast.makeText(this, "登录密码不能为空", Toast.LENGTH_LONG).show()
            pwd.requestFocus()
            pwd.setText("")
            flag = false
        }else if (pwd.text.toString().length < 6 || pwd.text.toString().length > 18){
            Toast.makeText(this, "密码只能在6—18位", Toast.LENGTH_LONG).show()
            pwd.requestFocus()
            pwd.setText("")
            flag = false
        }
        return flag
    }

    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        when(v?.id){
            R.id.pwd ->
                if (hasFocus){
                    phoneJudge()
                }
            R.id.notarize_pwd -> {
                if(hasFocus){
                    phonePwdJudge()
                }
            }
        }
    }

}

